package com.mysteel.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.mysteel.common.to.mq.SecKillOrderTo;
import com.mysteel.order.entity.OrderEntity;
import com.mysteel.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * ProjectName: mail
 * ClassName: OrderSecKillListener
 * Description:
 * date: 2021/04/13/013 14:33
 *
 * @author xiaochao
 */
@Slf4j
@Service
@RabbitListener(queues = {"order.seckill.order.queue"})
public class OrderSecKillListener {

    @Autowired
    private OrderService orderService;

    @RabbitHandler
    public void listenReleaseOrderQueue(Message message, Channel channel, SecKillOrderTo secKillOrderTo){
        try {
            log.info("准备创建秒杀单详细信息...");
            orderService.createSecKillOrder(secKillOrderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try {
                log.error("创建秒杀订单失败，消息重新入队...");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            } catch (IOException e1) {
                log.error("消息重新入队失败：{}", JSONObject.toJSONString(secKillOrderTo));
            }
        }


    }
}
